#include <stdio.h>
#include <string.h>
#include <unistd.h>

typedef struct _free_block_t {
    size_t size;
    struct _free_block_t *next;
} free_block_t;

static free_block_t free_block_list_head = { 0, 0 };
static const size_t align_to = 16;

void *malloc(size_t size)
{
    if (size <= 0) {
        return NULL;
    }
    size_t sz = size + sizeof(size_t);
    sz = (sz + (align_to-1)) & ~(align_to-1);
    free_block_t *prev = &free_block_list_head;
    free_block_t *curr = prev->next;
    while (curr) {
        if (curr->size >= sz) {
            return ((char *)curr) + sizeof(size_t);
        }
        prev = curr;
        curr = curr->next;
    }
    curr = (free_block_t *)sbrk(sz);
    curr->size = sz;
    return ((char *)curr) + sizeof(size_t);
}

void free(void *ptr)
{
    if (!ptr) { /* without this, printf crashes.. */
        return;
    }
    free_block_t *block = (free_block_t *)(((char *)ptr) - sizeof(size_t));
    block->next = free_block_list_head.next;
    free_block_list_head.next = block;
}

int main()
{
    char *str = malloc(128);
    char *str2 = malloc(1024);
    memset(str, 0, 128);
    memset(str2, 0, 1024);
    strcpy(str, "hello!");
    strcpy(str2, "hello!!!!!");
    printf("str=%s,str2=%s.\n", str, str2);
    free(str);
    free(str2);
    return 0;
}
